package com.tf8.treasure.interceptor;

import com.auth0.jwt.exceptions.JWTDecodeException;
import com.tf8.treasure.annotation.CheckLogin;
import com.tf8.treasure.entity.Session;
import com.tf8.treasure.enums.ReturnType;
import com.tf8.treasure.exception.RequestException;
import com.tf8.treasure.service.SessionService;
import com.tfg.mid.redis.RedisClient;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.tf8.treasure.utils.JwtUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;


@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    private SessionService sessionService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        //登录检查
        if (method.isAnnotationPresent(CheckLogin.class)) {
            CheckLogin checkToken = method.getAnnotation(CheckLogin.class);
            if (checkToken.required()) {
                String cookie = httpServletRequest.getHeader("cookie");
                // 执行认证
                if (StringUtils.isEmpty(cookie)) {
                    throw new RequestException(ReturnType.NOT_LOGIN);
                }
                Session session = sessionService.readSession(cookie);
                if(session == null){
                    throw new RequestException(ReturnType.COOKIE_EXPIRE);
                }
                return true;
            }
        }
        return true;
    }
  
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }


}